using UnityEngine;
using System.Collections;

/// \class  gkUtilitySphere
/// \brief  Sphere utility function
public class gkUtilitySphere 
{
	/// \brief  Convert spherical to cartesian coordinates
	public static Vector3 ConvertSphericalToCartesian(Vector3 a_f3SphericalPosition)
	{
		Vector3 f3CartesianPosition;
		
		f3CartesianPosition = Vector3.zero;
		
		// Convert the spherical position in cartesian coordinates
		f3CartesianPosition.x = a_f3SphericalPosition.x * Mathf.Sin(a_f3SphericalPosition.y * Mathf.Deg2Rad) * Mathf.Cos(a_f3SphericalPosition.z * Mathf.Deg2Rad);
		f3CartesianPosition.z = a_f3SphericalPosition.x * Mathf.Sin(a_f3SphericalPosition.y * Mathf.Deg2Rad) * Mathf.Sin(a_f3SphericalPosition.z * Mathf.Deg2Rad);
		f3CartesianPosition.y = a_f3SphericalPosition.x * Mathf.Cos(a_f3SphericalPosition.y * Mathf.Deg2Rad);
		
		return f3CartesianPosition;
	}
	
	/// \brief  Convert cartesian to spherical coordinates
	public static Vector3 ConvertCartesianToSpherical(Vector3 a_f3CartesianPosition)
	{
		Vector3 f3SphericalPosition;
		float fDistanceToYAxis;
		
		f3SphericalPosition = Vector3.zero;
		
		// Convert the cartesian position in spherical coordinates
		f3SphericalPosition.x = Mathf.Sqrt(a_f3CartesianPosition.x * a_f3CartesianPosition.x +
		                            a_f3CartesianPosition.y * a_f3CartesianPosition.y +
		                            a_f3CartesianPosition.z * a_f3CartesianPosition.z);
		
		// If rho=0 phi can be any angle
		// for the temporal continuity sake we doesn't modify it if rho=0
		// else we compute phi based on the cartesian coordinate
		if(f3SphericalPosition.x != 0)
		{
			f3SphericalPosition.y = Mathf.Rad2Deg * Mathf.Acos(a_f3CartesianPosition.y/f3SphericalPosition.x);
		}
		
		// Compute theta
		// If distance to z axis = 0 theta can be any angle
		// for the temporal continuity sake we doesn't modify it if distance to z axis  = 0
		// else we compute theta based on the cartesian coordinate
		fDistanceToYAxis = Mathf.Sqrt(a_f3CartesianPosition.x * a_f3CartesianPosition.x + a_f3CartesianPosition.z * a_f3CartesianPosition.z);
		if(fDistanceToYAxis != 0.0f)
		{
			if(a_f3CartesianPosition.z >= 0.0f)
			{
				f3SphericalPosition.z = Mathf.Rad2Deg * Mathf.Acos(a_f3CartesianPosition.x/fDistanceToYAxis);
			}
			else
			{
				f3SphericalPosition.z = 360.0f - Mathf.Rad2Deg * Mathf.Acos(a_f3CartesianPosition.x/fDistanceToYAxis);
			}
		}
		
		return f3SphericalPosition;
	}
}
